package com.icezzz.scan_folder;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

public class FolderScan {

	public static void scan(String folder) {
		File root = new File(folder);
		File[] listFiles = root.listFiles();
		List<FileInfo> list = new ArrayList<>();
		List<FileInfo> sub = new ArrayList<>();
		for (File subFile : listFiles) {
			String absolutePath = subFile.getAbsolutePath();
			absolutePath = absolutePath.replace("\\", "/");
			long size = 0;
			if (subFile.isDirectory()) {
				size = scan(subFile, sub);
			} else {
				size = FileUtil.size(subFile);
			}
			FileInfo fileInfo = fileInfo(absolutePath, size, 1);
			list.add(fileInfo);
		}
		System.out.println("=============一级目录==============");
		list = sort(list);
		print(list, 10);
		System.out.println("=============二级目录==============");
		sub = sort(sub);
		print(sub, 10);
	}

	private static void print(List<FileInfo> list, int limit) {
		limit = Math.min(list.size(), limit);
		for (int i = 0; i < limit; i++) {
			FileInfo fileInfo = list.get(i);
			String name = fileInfo.getName();
			long size = fileInfo.getSize();
			String sizeStr = size + "";
			String mainStr = size / (1024 * 1024) + "";
			String left = StrUtil.padPre(sizeStr, 20, " ");
			String head = StrUtil.padPre(mainStr, 17, " ");
			String sum = head + " >> " + left + " >> " + name;
			System.out.println(sum);
		}

	}

	private static List<FileInfo> sort(List<FileInfo> list) {
		list = list.stream().sorted(Comparator.comparingLong(FileInfo::getSize).reversed())
				.collect(Collectors.toList());
		return list;
	}

	private static long scan(File folder, List<FileInfo> sub) {
		File[] listFiles = folder.listFiles();
		long sum = 0;
		for (File subFile : listFiles) {
			String absolutePath = subFile.getAbsolutePath();
			absolutePath = absolutePath.replace("\\", "/");
			long size = FileUtil.size(subFile);
			sum += size;
			FileInfo fileInfo = fileInfo(absolutePath, size, 2);
			sub.add(fileInfo);
		}
		return sum;
	}

	public static FileInfo fileInfo(String name, long size, int level) {
		FileInfo fileInfo = new FileInfo();
		fileInfo.setName(name);
		fileInfo.setSize(size);
		fileInfo.setLevel(level);
		return fileInfo;
	}

}
